package com.cucn.ingmall.order.web;

import com.cucn.common.exception.NoStockException;
import com.cucn.ingmall.order.interceptor.LoginUserInterceptor;
import com.cucn.ingmall.order.service.OrderService;
import com.cucn.ingmall.order.vo.OrderConfirmVO;
import com.cucn.ingmall.order.vo.OrderSubmitVO;
import com.cucn.ingmall.order.vo.SubmitOrderResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.concurrent.ExecutionException;

/**
 * @author KouChaoJie
 * @since: 2022/1/19 09:45
 */
@Slf4j
@Controller
public class OrderWebController {
    @Resource
    private OrderService orderService;

    /**
     * 去结算,跳转订单确认页
     */
    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        log.info("用户id:{},结算订单前往确认页", LoginUserInterceptor.loginUser.get().getId());
        //向页面展示订单确认信息
        OrderConfirmVO confirmVO = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", confirmVO);
        return "confirm";
    }

    /**
     * 提交订单
     * submitOrder
     * 创建订单,验令牌,验价格,锁库存
     *
     * @param vo 提交的订单数据
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVO vo, Model model, RedirectAttributes redirectAttributes) {
        log.info("订单确认页提交的数据..{}", vo);
        try {
            //提交订单的逻辑
            SubmitOrderResponseVO submitOrderResponse = orderService.submitOrder(vo);
            log.info("生成的订单数据:{}", submitOrderResponse);

            if (submitOrderResponse.getCode() == 0) {
                //下单成功来到支付选择页
                model.addAttribute("submitOrderResp", submitOrderResponse);
                return "pay";
            } else {
                String msg = "下单失败:";
                switch (submitOrderResponse.getCode()) {
                    case 1:
                        msg = msg + "订单信息过期,请刷新再次提交";
                        break;
                    case 2:
                        msg = msg + "订单商品价格发生变化,请重新添加商品";
                        break;
                    case 3:
                        msg = msg + "锁定库存失败,商品库存不足";
                        break;
                }
                redirectAttributes.addFlashAttribute("msg", msg);
                //下单失败重新回到订单确认页
                return "redirect:http://order.koukoucoding.xn--fiqs8s/toTrade";
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof NoStockException) {
                String message = e.getMessage();
                redirectAttributes.addFlashAttribute("msg", message);
            }
            return "redirect:http://order.koukoucoding.xn--fiqs8s/toTrade";
        }
    }
}
